package ServerOperation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;

import Boundry.EvaluationPanel;
import Controllers.GlobalData;
import Controllers.GenericToolsForController.PDFfile;
import Entity.EvaluationReport;
import Entity.Message;
import Entity.Report;
import Entity.Request;
import Entity.TestingFailureReport;
import Entity.User;
import Entity.Worker;

public class DBReport  implements IDBHandler {
	
	private Connection conn;
	public DBReport(Connection conn) {
		super();
		this.conn = conn;
	}

	@Override
	public Message decipherMessage(Message msg) {
		// TODO Auto-generated method stub
		Message AnswerMessage = null;
		int op = (msg.getOpCode()%1000);
	
		switch (op){
		case 1:
			AnswerMessage = createNewEvaluationReport(msg);
			break;
		case 2:
			AnswerMessage = createNewTestingReport(msg);
			break;
		case 3:
			break;
		case 4:
			break;
		case 5:
			break;
		case 6:
			break;
		case 7:
			break;
		
		}
		return AnswerMessage;
	}
	
	
	private Message createNewTestingReport(Message msg) {
		Report report = null;
		if (msg.getDataGram() instanceof Report)
		{
           report = (Report) msg.getDataGram();
		}
		else
		{
			return new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
		}
		if (report == null)
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(), new Integer(-1));
			return ansMessage;
		}	
		
		//String newTestingFailureReportFilePath =null;
		String currentDir = System.getProperty("user.dir");
		String path = currentDir+"\\";
		File dir=new File(path);
		if(! dir.exists())
		{
			dir.mkdir();
			System.out.println("Creats new dir : "+path);
		}
		
		path = path +report.getCreator().getId()+"\\";
		 dir=new File(path);

		if(! dir.exists())
		{
			dir.mkdir();
			System.out.println("Creats new dir : "+path);
		}
		
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		path+="TestingFailureReport"+sdf.format(new Date())+".pdf";
		report.getPdfFile().write(path);
		int reportId = GenricOperation.getNextId("report",conn);
		int creatorID;
        creatorID= ((Worker)report.getCreator()).getId();
        path = path.replace('\\' , '/');
		String SpecficQuery = new String("Insert Into report (id,File,Creator) Values ("+reportId+",'"+path+"',"+creatorID+")");
		System.out.println(SpecficQuery);
		Statement stmt;
		try 
		{
		stmt = conn.createStatement();
		
		//ResultSet rs = stmt.executeQuery(SpecficQuery);
		int ok = stmt.executeUpdate(SpecficQuery);
		//System.out.println(rs.toString());
		if (ok == 1)
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(reportId) );
			stmt.close();
			return ansMessage;
		}
		else
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
			return ansMessage;
			
		}
		
		}
		catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
	}

	public Message createNewEvaluationReport(Message msg)
	{
		Report report = null;
		if (msg.getDataGram() instanceof Report)
		{
           report = (Report) msg.getDataGram();
		}
		else
		{
			return new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
		}
		if (report == null)
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(), new Integer(-1));
			return ansMessage;
		}	
		
		String newEvaluationReportFilePath =null;
		String currentDir = System.getProperty("user.dir");
		String path = currentDir+"\\";
		File dir=new File(path);
		if(! dir.exists())
		{
			dir.mkdir();
			System.out.println("Creats new dir : "+path);
		}
		
		path = path +report.getCreator().getId()+"\\";
		 dir=new File(path);

		if(! dir.exists())
		{
			dir.mkdir();
			System.out.println("Creats new dir : "+path);
		}
		
//	String startDateOfCreation = new SimpleDateFormat("yyyy-MM-dd").format(dateOfCreation);
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		path+="EvaluationReport"+sdf.format(new Date())+".pdf";
		report.getPdfFile().write(path);
		int reportId = GenricOperation.getNextId("report",conn);
		int creatorID;
        creatorID= ((Worker)report.getCreator()).getId();
        path = path.replace('\\' , '/');
		String SpecficQuery = new String("Insert Into report (id,File,Creator) Values ("+reportId+",'"+path+"',"+creatorID+")");
		System.out.println(SpecficQuery);
		Statement stmt;
		try 
		{
		stmt = conn.createStatement();
		
		//ResultSet rs = stmt.executeQuery(SpecficQuery);
		int ok = stmt.executeUpdate(SpecficQuery);
		//System.out.println(rs.toString());
		if (ok == 1)
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(reportId) );
			stmt.close();
			return ansMessage;
		}
		else
		{
			Message ansMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
			return ansMessage;
			
		}
		
		}
		catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  new Message(msg.getOpCode()+1000, msg.getMessageID(),  new Integer(-1));
	}

public String createEvaluationFileInServer(EvaluationReport report)
{
	//build the path to file
	String currentDir = System.getProperty("user.dir");
	String path = currentDir+"\\";
	File dir=new File(path);
	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	path = (path + (report.getCreator().getUsername().replaceAll(" ", "_").replaceAll(":", "_"))+"\\");
	 dir=new File(path);
	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	Request req = GlobalData.request;
	if (req != null)
	{
	   path = path + req.getRequestId()+"\\";
	}
	else
	{
		path = path + "general";
	}
	 dir=new File(path);

	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	
	//we decide the file name
	String fileName =  path + "EvaluationReport_"+(report.getDateOfCreation().toString().replaceAll(" ", "_").replaceAll(":", "_")) + ".pdf";
	System.out.println(fileName);
	//actually creates a copy of file
    PDFfile evalReportPDF = new PDFfile( report,  fileName); 
    System.out.println(fileName);
    fileName = fileName.replace('\\' , '/');
    System.out.println(fileName);
	return fileName;
}


public String createTestingFailureFileInServer(Report report)
{
	//build the path to file
	String currentDir = System.getProperty("user.dir");
	String path = currentDir+"\\";
	File dir=new File(path);
	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	path = (path + (report.getCreator().getUsername().replaceAll(" ", "_").replaceAll(":", "_"))+"\\");
	 dir=new File(path);
	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	Request req = GlobalData.request;
	if (req != null)
	{
	   path = path + req.getRequestId()+"\\";
	}
	else
	{
		path = path + "general";
	}
	 dir=new File(path);

	if(! dir.exists())
	{
		dir.mkdir();
		System.out.println("Creats new dir : "+path);
	}
	
	//we decide the file name
	String fileName =  path + "TestingFailureReport_"+(report.getDateOfCreation().toString().replaceAll(" ", "_").replaceAll(":", "_")) + ".pdf";
	System.out.println(fileName);
	//actually creates a copy of file
    PDFfile testingFailureReportPDF = new PDFfile( report,  fileName); 
    System.out.println(fileName);
    fileName = fileName.replace('\\' , '/');
    System.out.println(fileName);
	return fileName;
}
}
